package org.isource.servlet;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.isource.common.PMF;
import org.isource.common.Utils;
import org.isource.pojo.Comment;


@SuppressWarnings("serial")
public class QueryCommentDetails extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(QueryCommentDetails.class
			.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String requestURI = req.getRequestURI();
		log.info("### requestURI=" + requestURI);
		Long thirdPartyId = Utils.getThirdPartyId(requestURI);
		log.info("### thirdPartyId=" + thirdPartyId);
		String fileName = Utils.getFileName(requestURI);
		log.info("### fileName=" + fileName);
		Integer lineNumber = Utils.getLineNumber(requestURI);
		log.info("### lineNumber=" + lineNumber);
		
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    
	    Query query = pm.newQuery(Comment.class);
	    query.declareParameters(
	        "Long thirdPartyIdInput, String fileNameInput, Integer lineNumberInput");
	    StringBuilder filter = new StringBuilder();
	    filter.append("thirdPartyId == thirdPartyIdInput").append(" && ");
	    filter.append("fileName == fileNameInput").append(" && ");
	    filter.append("lineNumber == lineNumberInput");
	    
	    if (filter.length() > 0) {
	      query.setFilter(filter.toString());
	    }
	    
	    List<Comment> comments =  (List<Comment>) query.execute(thirdPartyId, fileName, lineNumber);

	    int i = 0;
	    for (Comment comment : comments) {
	    	log.info("### Comment" + i++ + "=" + comment.toString());
		}	    
	    
	    resp.setContentType("text/html;charset=UTF-8");
	    
		resp.getWriter().println(Utils.makeHTMLSnippet(comments));
	}
}
